package com.levelup.cr.client.mvc;

import com.google.gwt.cell.client.*;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import com.levelup.cr.model.dto.NodeTransfer;

import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Created with IntelliJ IDEA.
 * User: denis_zavadsky
 * Date: 9/26/13
 * Time: 7:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class RepositoryTreeViewModel implements TreeViewModel{
    private Logger logger = Logger.getLogger("RepositoryTreeViewModel");
    final SelectionModel<NodeTransfer> selectionModel;
    final Cell<NodeTransfer> customCell;

    public RepositoryTreeViewModel(final SelectionModel<NodeTransfer> selectionModel) {
        this.selectionModel = selectionModel;
        logger.log(Level.SEVERE,"RepositoryTreeViewModel Constructor");
        customCell = new AbstractCell<NodeTransfer>(){
            @Override
            public void render(Context context, NodeTransfer value, SafeHtmlBuilder sb) {

               logger.log(Level.SEVERE,"CustomCell value="+value.getName());
               sb.appendHtmlConstant("<span>" + value.getName() + "</span>");
            }


        };
    }

    @Override
    public <T> NodeInfo<?> getNodeInfo(T value) {
        logger.log(Level.SEVERE,"getNodeInfo called");
        if (value instanceof NodeTransfer){
            logger.log(Level.SEVERE,"Value: "+ ((NodeTransfer) value).getName());
        }
        ListDataProvider<NodeTransfer> dataProvider = new ListDataProvider<NodeTransfer>();
        if (value instanceof NodeTransfer){
            if (((NodeTransfer) value).getChilds()!=null){
                for (NodeTransfer child: ((NodeTransfer) value).getChilds()) {
                    dataProvider.getList().add(child);
                }
            }
        }
        logger.log(Level.SEVERE,"getNodeInfo before return value");
        // Return a node info that pairs the data with a cell.
        return new DefaultNodeInfo<NodeTransfer>(dataProvider, customCell);
    }

    @Override
    public boolean isLeaf(Object value) {
        logger.log(Level.SEVERE,"isLeaf called");
        if (value instanceof NodeTransfer){
            if (((NodeTransfer) value).getChilds()!=null && !((NodeTransfer) value).getChilds().isEmpty()){
               return false;
            }
        }
        return true;
    }


}
